package com.magist.core.controller;

import com.magist.core.constants.AppConstants;
import com.magist.core.entity.Page;
import com.magist.core.http.HttpHolder;
import com.magist.core.util.TxtUtil;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 君昱
 * 抽象controller类
 */
public abstract class BaseController {

    protected ModelAndView createMV(String name) {
        ModelAndView mv= new ModelAndView(name);
        return mv;
    }

    public HttpServletRequest getRequest() {
        return HttpHolder.getHttpRequest();
    }

    protected Page getPageInfo(){
        Integer page = getParamInt("page");
        Integer rows = getParamInt("page.limit");
        String sort = getParamStr("page.sort");
        String order = getParamStr("page.order");

        if (page <= 0) {
            page=1;
        }
        if(rows<=0) {
            rows= AppConstants.PAGE_LIMIT;
        }
        if (TxtUtil.isEmpty(sort)) {
            return new Page(page, rows);
        } else {
            return new Page(page, rows, sort, order);
        }
    }

    /**
     * 获取字符串参数
     * @param param
     * @return
     */
    protected String getParamStr(String param) {
        String value = getRequest().getParameter(param);
        if (value == null)
            value = "";
        return value;
    }

    /**
     * 获取整数参数
     * @param param
     * @return
     */
    protected Integer getParamInt(String param) {
        String value = getRequest().getParameter(param);
        if (value == null)
            return 0;
        return Integer.parseInt(value);
    }

    public HttpServletResponse getResponse() {
        return HttpHolder.getHttpResponse();
    }
}
